<?php
// инициализация приложения (БД, сессия)
include dirname(__FILE__) . '/../../config.php';

function check_id($data)
{
    $data = abs((int)$data);
    $data = mysql_real_escape_string(strip_tags(trim($data)));
    return $data;
}

//funkciya ekranirovaniya
function check_string($data)
{
    $data = mysql_real_escape_string(strip_tags(trim($data)));
    return $data;
}

function check_empty($data, $data2 = false, $data3 = false, $data4 = false)
{
    if($data2 = true && $data3 = true && $data4 = true)
    {
        if($data == '' || $data2 == '' || $data3 == '' || $data4 == '')
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    else
    {
        if($data == '')
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

//funkciya udaleniya fayla
function deletfile($directory,$filename)
{
  // открываем директорию (получаем дескриптор директории)
  $dir = opendir($directory);
  
  // считываем содержание директории
while(($file = readdir($dir)))
{
          // Если это файл и он равен удаляемому ...
  if((is_file("$directory/$file")) && ("$directory/$file" == "$directory/$filename"))
  {
    // ...удаляем его.
    unlink("$directory/$file");
                  
     // Если файла нет по запрошенному пути, возвращаем TRUE - значит файл удалён.
    if(!file_exists($directory."/".$filename))
    {
        return true;   
    }
  }
}
  // Закрываем дескриптор директории.
  closedir($dir);
}

//vivodim libo randomno 9 saytov s luboy kategorii, libo vse s konkretnoy
function get_data($id_category = false)
{
    if($id_category)
    {
        $id_category = check_id($id_category);
        
        $query = "SELECT s.id_site, s.site_url, s.description, s.screenshot, c.name
                  FROM {$dbPrefix}sc__sites AS s
                  JOIN {$dbPrefix}sc__categorys AS c ON s.id_category = c.id_category
                  WHERE s.id_category = $id_category ORDER BY id_site DESC";
    }
    else
    {
        $query = "SELECT * FROM {$dbPrefix}sc__sites ORDER BY RAND() LIMIT 9";
    }

	$result = mysql_query($query);

	if (!$result)
		die(mysql_error());

 	$n = mysql_num_rows($result);    
 	$sites = array();    
 	for ($i = 0; $i < $n; $i++)
 	{
 		$row = mysql_fetch_assoc($result);
 		$sites[] = $row;
 	}
         
 	return $sites;
}
// poluchaem konkretniy sayt dlyta redaktirovaniya
function get_cpecific($id)
{
    $id = check_id($id);    
    
    $tmp = "SELECT id_site, site_url, description, id_category, screenshot
              FROM {$dbPrefix}sc__sites
              WHERE id_site = '%d'";
    $query = sprintf($tmp, $id);
    $result = mysql_query($query);
    
    if (!$result)
		die(mysql_error());

 	$n = mysql_num_rows($result);    
 	$site = array();    
 	for ($i = 0; $i < $n; $i++)
 	{
 		$row = mysql_fetch_assoc($result);
 		$site[] = $row;
 	}
         
 	return $site;
    
}
//sohranyaem dannie
function update_data($id_site, $site_url, $description, $category)
{
    
    $id_site = check_id($id_site);
    $site_url = check_string($site_url);
    $description = check_string($description);
    $category = check_id($category);
    //proveryayu esli bil zagrujen noviy screenshot ili net i vipolnyayu zapros
    if(isset($_FILES['screen']) && file_exists($_FILES['screen']['tmp_name']))
    {
        //poluchayu fail i zamenyayu ego imya na id
        $path = 'img/';
        $old_name = $_FILES['screen']['name'];
        $name = "$id_site.jpg";
        $old_name = $name;
        $path = $path.$old_name;
        
        $temp_path = $_FILES['screen']['tmp_name'];
        
        copy($temp_path, $path);
        
        $tmp = "UPDATE {$dbPrefix}sc__sites SET site_url = '%s',                                            
                                                description = '%s',
                                                id_category = '%d',
                                                screenshot = '%s'
                                            WHERE id_site = '%d'";
        $query = sprintf($tmp, $site_url, $description, $category, rtrim($old_name, ".jpg"), $id_site);
    }
    else
    {
        $tmp = "UPDATE {$dbPrefix}sc__sites SET site_url = '%s',                                            
                                                description = '%s',
                                                id_category = '%d'
                                            WHERE id_site = '%d'";
        $query = sprintf($tmp, $site_url, $description, $category, $id_site);
    }
    
    
    $result = mysql_query($query);
    if (!$result)
		die(mysql_error());
        
    return mysql_affected_rows();    
}
//udalyaem screenshot
function delete_img($num_of_screen)
{
    $num_of_screen = check_id($num_of_screen);
    $path = "img";
    $name = "$num_of_screen.jpg";
    $del_file = deletfile($path, $name);
    if($del_file)
    {
        $tmp = "UPDATE {$dbPrefix}sc__sites SET screenshot = NULL WHERE id_site = '%d'";
        $query = sprintf($tmp, $num_of_screen);
        $result = mysql_query($query);
    
    	if (!$result)
    		die(mysql_error());
        header("Location: index.php?id=$num_of_screen");
        exit;
    }
}

//udalyaem sayt
function delete_data($id, $id_cat)
{
    $id = check_id($id);
    $id_cat = check_id($id_cat);    
    
    $tmp = "DELETE FROM {$dbPrefix}sc__sites WHERE id_site = '%d'";
    $query = sprintf($tmp, $id);
    $result = mysql_query($query);

	if (!$result)
		die(mysql_error());
    header("Location: index.php?cat=$id_cat");
    exit;
}

//poluchaem menu cherez bazu
function get_menu()
{    
    $query = "SELECT * FROM {$dbPrefix}sc__categorys ORDER BY id_category";
    
    $result = mysql_query($query);

	if (!$result)
		die(mysql_error());

 	$n = mysql_num_rows($result);    
 	$categorys = array();    
 	for ($i = 0; $i < $n; $i++)
 	{
 		$row = mysql_fetch_assoc($result);
 		$categorys[] = $row;
 	}
         
 	return $categorys;   
}

$edit = get_cpecific($_GET['id']);
$menu = get_menu();
$num_of_menu = count($menu);
define('Q_EL_STRING', 3);
if(isset($_GET['cat']))
{
    $data = get_data($_GET['cat']);
    $num_of_sites = count($data);
    $counter = 0;               
}
else
{
    $data = get_data(); 
}
//udalyaem kartinku
if(isset($_GET['img']))
{
    delete_img($_GET['img']);
}

//udalyaem sayt
if(isset($_POST['delete']))
{
    delete_data($_POST['id'], $_POST['category']);
}

if(isset($_POST))
{
    update_data($_POST['id'],$_POST['site_url'],$_POST['description'],$_POST['category']);
}
/////////////////////////////////////////
if(isset($_GET['id']))
{
    include_once('tpl/edit-form.php');
}
else
{
    include_once('tpl/main.php');       
}
var_dump($data2);
?>